package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 添加工单
     *
     * @param taskViewModel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createTask(TaskViewModel taskViewModel) {
        //效验售货机状态
        checkCreateTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());
        //效验同一台设备是否有未完成同类型工单
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器由未完成的同类型工单");
        }
        /**
         * 新增工单表记录
         */
        TaskEntity taskEntity = new TaskEntity();
        //工单编号
        taskEntity.setTaskCode(generateTaskCode());
        //属性复制
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        //售货机状态
        taskEntity.setTaskStatus(VMSystem.VM_STATUS_RUNNING);
        //区域id
        VmVO vmInfo = vmService.getVMInfo(taskEntity.getInnerCode());
        taskEntity.setRegionId(vmInfo.getRegionId());
        //点位地址
        taskEntity.setAddr(vmInfo.getNodeAddr());
        //工单类型
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        //判断工单类型是否属于补货工单
        if (taskEntity.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            taskViewModel.getDetails().forEach(taskDetailsViewModel -> {
                TaskDetailsEntity details = new TaskDetailsEntity();
                BeanUtils.copyProperties(taskDetailsViewModel, details);
                details.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(details);
            });
        }
        this.save(taskEntity);
        updateTaskZSet(taskEntity,1);
        return true;
    }

    /**
     * 接收工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity byId = this.getById(id);
        //判断工单状态是否是待处理状态
        if (!byId.getTaskStatus().equals(VMSystem.TASK_STATUS_CREATE)) {
            throw new LogicException("工单不是待处理状态");
        }
        //修改工单状态
        byId.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.save(byId);
    }

    /**
     * 取消工单
     *
     * @param id     执行者id
     * @param cancel 拒绝理由
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancel) {
        //查询工单信息
        TaskEntity byId = this.getById(id);
        //判断工单状态
        if (byId.getTaskStatus().equals(VMSystem.TASK_STATUS_CANCEL) || byId.getTaskStatus().equals(VMSystem.TASK_STATUS_FINISH)) {
            throw new LogicException("工单已结束");
        }
        byId.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        byId.setDesc(cancel.getDesc());

        updateTaskZSet(byId,-1);
        return this.save(byId);
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(Long id) {
        TaskEntity byId = this.getById(id);
        //判断工单状态
        if (byId.getTaskStatus().equals(VMSystem.TASK_STATUS_CANCEL) || byId.getTaskStatus().equals(VMSystem.TASK_STATUS_FINISH)) {
            throw new LogicException("工单已消失");
        }
        //修改工单状态
        byId.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(byId);
        //判断工单类型
        if (byId.getProductTypeId().equals(VMSystem.TASK_TYPE_DEPLOY) || byId.getProductTypeId().equals(VMSystem.TASK_TYPE_REVOKE)) {
            //运维工单的封装与下发
            noticeVMServiceStatus(byId);
        }
        if (byId.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            //补货工单的封装与下发
            noticeVMServiceSupply(byId);
        }
        return true;
    }

    /**
     * 获取同一天内分配的工单最少的人
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002";
        if (isRepair) {
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId + roleCode;
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 1);
        if (range == null || range.isEmpty()) {
            throw new LogicException("该区域暂时没有工作人员");
        }
        return (Integer) range.stream().collect(Collectors.toList()).get(0);
    }

    /**
     * 补货工单的封装与下发
     * @param byId
     */
    private void noticeVMServiceSupply(TaskEntity byId) {
        /**
         * 向售货机微服务发送消息
         */
        QueryWrapper<TaskDetailsEntity> Wrapper = new QueryWrapper<>();
        //跟据id查询工单明细表
        LambdaQueryWrapper<TaskDetailsEntity> eq = Wrapper.lambda()
                .eq(TaskDetailsEntity::getTaskId, byId.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(eq);

        SupplyContract supplyContract = new SupplyContract();
        //封装售货机编号
        supplyContract.setInnerCode(byId.getInnerCode());
        List<SupplyChannel> supplyChannels = Lists.newArrayList();
        details.forEach(d ->{
            SupplyChannel channel = new SupplyChannel();
            channel.setChannelId(d.getChannelCode());
            channel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(channel);
        });
        supplyContract.setSupplyData(supplyChannels);
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyChannels);
        } catch (Exception e) {
            log.info("发送工单完成协议错误");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 运维工单的封装与下发
     * @param byId
     */
    private void noticeVMServiceStatus(TaskEntity byId) {
        /**
         * 向售货机微服务发送消息
         */
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        //封装工单类型
        taskCompleteContract.setTaskType(byId.getProductTypeId());
        //封装售货机编号
        taskCompleteContract.setInnerCode(byId.getInnerCode());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (Exception e) {
            log.info("发送工单完成协议错误");
            throw new LogicException("发送工单完成协议出错");
        }

    }

    /**
     * 效验同一台设备是否有未完成同类型工单
     *
     * @param innerCode     售货机编号
     * @param productTypeId 工单类型
     * @return
     */
    private boolean hasTask(String innerCode, int productTypeId) {
        QueryWrapper<TaskEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(TaskEntity::getProductTypeId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productTypeId)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(wrapper) > 0;
    }

    /**
     * 效验售货机状态
     *
     * @param innerCode     售货机编号
     * @param productTypeId 工单类型
     */
    private void checkCreateTask(String innerCode, int productTypeId) {
        //跟据设备编号获取售货机信息
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if (vmInfo == null) {
            throw new LogicException("为查询到设备，设备效验失灵");
        }
        //如果是投放工单
        if (productTypeId == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("设备已在运营状态");
        }

        //如果是补货工单
        if (productTypeId == VMSystem.TASK_TYPE_SUPPLY && !vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("设备处于非运营状态");
        }

        //如果是撤机工单
        if (productTypeId == VMSystem.TASK_TYPE_REVOKE && !vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("设备处于非运营状态");
        }
    }

    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        //跟据日期生成编号
        String mdd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        String key = "lkd.task.code." + mdd;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return mdd + "0001";
        }
        return mdd + Strings.padStart(
                redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    /**
     * 更新工单量列表
     * @param taskEntity
     * @param score 增加的分值
     */
    private void updateTaskZSet(TaskEntity taskEntity,int score){
        //运维人员
        String role = "1003";
        if (taskEntity.getProductTypeId().intValue() == 2){
            //运营人员
            role = "1002";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + role;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
    }


}
